// 检查登录状态
function checkAuth() {
    const token = localStorage.getItem('token');
    if (!token) {
        window.location.href = '/admin/login';
    }
    return token;
}

// 显示错误消息
function showError(message) {
    const alertDiv = $('<div class="alert alert-danger alert-dismissible fade show" role="alert">' +
        message +
        '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
        '</div>');
    $('.container').prepend(alertDiv);
    setTimeout(() => alertDiv.alert('close'), 5000);
}

// 显示成功消息
function showSuccess(message) {
    const alertDiv = $('<div class="alert alert-success alert-dismissible fade show" role="alert">' +
        message +
        '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>' +
        '</div>');
    $('.container').prepend(alertDiv);
    setTimeout(() => alertDiv.alert('close'), 5000);
}

// 更新用户状态
function updateUserStatus(userId, newStatus) {
    if (!confirm('确定要' + (newStatus === 1 ? '启用' : '禁用') + '该用户吗？')) {
        return;
    }

    $.ajax({
        url: `/api/admin/users/${userId}/status`,
        method: 'PUT',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: { status: newStatus },
        success: function() {
            showSuccess('用户状态更新成功');
            loadUsers();
        },
        error: function() {
            showError('用户状态更新失败');
        }
    });
}

// 删除用户
function deleteUser(userId) {
    if (!confirm('确定要删除该用户吗？此操作不可恢复！')) {
        return;
    }

    $.ajax({
        url: `/api/admin/users/${userId}`,
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        success: function() {
            showSuccess('用户删除成功');
            loadUsers();
        },
        error: function() {
            showError('用户删除失败');
        }
    });
}

// 更新维修工状态
function updateRepairmanStatus(repairmanId, newStatus) {
    if (!confirm('确定要' + (newStatus === 1 ? '启用' : '禁用') + '该维修工吗？')) {
        return;
    }

    $.ajax({
        url: `/api/admin/repairmen/${repairmanId}/status`,
        method: 'PUT',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: { status: newStatus },
        success: function() {
            showSuccess('维修工状态更新成功');
            loadRepairmen();
        },
        error: function() {
            showError('维修工状态更新失败');
        }
    });
}

// 删除维修工
function deleteRepairman(repairmanId) {
    if (!confirm('确定要删除该维修工吗？此操作不可恢复！')) {
        return;
    }

    $.ajax({
        url: `/api/admin/repairmen/${repairmanId}`,
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        success: function() {
            showSuccess('维修工删除成功');
            loadRepairmen();
        },
        error: function() {
            showError('维修工删除失败');
        }
    });
}

// 更新订单状态
function updateOrderStatus(orderId, newStatus) {
    if (!confirm('确定要更新订单状态吗？')) {
        return;
    }

    $.ajax({
        url: `/api/admin/orders/${orderId}/status`,
        method: 'PUT',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        data: { status: newStatus },
        success: function() {
            showSuccess('订单状态更新成功');
            loadOrders();
        },
        error: function() {
            showError('订单状态更新失败');
        }
    });
}

// 删除订单
function deleteOrder(orderId) {
    if (!confirm('确定要删除该订单吗？此操作不可恢复！')) {
        return;
    }

    $.ajax({
        url: `/api/admin/orders/${orderId}`,
        method: 'DELETE',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        success: function() {
            showSuccess('订单删除成功');
            loadOrders();
        },
        error: function() {
            showError('订单删除失败');
        }
    });
}

// 查看订单详情
function viewOrderDetail(orderId) {
    window.location.href = `/admin/order-detail?id=${orderId}`;
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 获取订单状态文本
function getOrderStatusText(status) {
    const statusMap = {
        0: '待接单',
        1: '已接单',
        2: '维修中',
        3: '已完成',
        4: '已取消'
    };
    return statusMap[status] || '未知状态';
}

// 页面加载完成后检查登录状态
$(document).ready(function() {
    checkAuth();
}); 